<!--
 * @Author: xiuquanxu
 * @Company: kaochong
 * @Date: 2021-01-08 14:59:36
 * @LastEditors: xiuquanxu
 * @LastEditTime: 2021-01-08 17:19:12
-->
<html>
    <meta charset="utf-8">
    <body>
        <div>
            <span>1</span>
            <div>
                <div>
                    <span>3</span>
                </div>
                <p>
                    <div>
                        <span>4</span>
                    </div>
                </p>
            </div>
            <div>
                <span>2</span>
            </div>
        </div>
    </body>
</html>
<script>
    const body = document.body;
    function bfs(root, tag) {
        const stack = [];
        const res = [];
        stack.push(root);
        while(stack.length > 0) {
            // 方法1
            // for (let i = 0, len = stack.length; i < len; i += 1) {
            //     const item = stack.shift();
            //     if (item.tagName === tag) {
            //         res.push(item.textContent);
            //     }
            //     for (let j = 0, lenn = item.children.length; j < lenn; j += 1) {
            //         stack.push(item.children[j]);
            //     }
            // }
            // 方法2
            const item = stack.shift();
            for (let i = 0, len = item.children.length; i < len; i += 1) {
                stack.push(item.children[i]);
            }
            if (item.tagName === tag) {
                res.push(item.textContent);
            }
        }
        return res;
    }
    function dfs(root, tag) {
        const stack = [];
        const res = [];
        stack.push(root);
        while(stack.length > 0) {
            const item = stack[stack.length - 1];
            let count = 0;
            for (let i = 0 ,len = item.children.length; i < len; i += 1) {
                if (!item.children[i].visit) {
                    stack.push(item.children[i]);
                    item.children[i].visit = true;
                    if (item.children[i].tagName === tag) {
                        res.push(item.children[i].textContent);
                    }
                    break;
                } else {
                    count += 1;
                }
            }
            if (!item.children || count === item.children.length) {
                stack.pop();
            }
        }
        return res;
    }
    console.log(bfs(body, 'SPAN'));
    console.log(dfs(body, 'SPAN'));
    console.log(body);
</script>